//
//  OBMomentViewModel.m
//  WeChat
//
//  Created by 黄柳姣 on 2018/5/2.
//  Copyright © 2018年 obally. All rights reserved.
//  朋友圈ViewModel

#import "OBMomentViewModel.h"
#import "OBDataRequest.h"
#import "OBMomentModel.h"
#import "OBMomentItemViewModel.h"
#import "OBUserModel.h"
#import "OBMomentProfileViewModel.h"

@interface OBMomentViewModel ()

/// 刷新某一个section的 事件回调
@property (nonatomic, readwrite, strong) RACSubject *reloadSectionSubject;

/// 富文本文字上的事件处理
@property (nonatomic, readwrite, strong) RACCommand *attributedTapCommand;
/// 个人用户信息
@property (nonatomic, readwrite, strong) RACCommand *userProfileCommand;
/// 个人信息头部视图模型
@property (nonatomic, readwrite, strong) OBMomentProfileViewModel *profileViewModel;
@property (nonatomic, copy)NSMutableArray *allItemViewModels;//所有的数据  二维数组  每组存5条

@end
@implementation OBMomentViewModel
- (void)initialize
{
    [super initialize];
    @weakify(self);
    //隐藏导航栏
    self.prefersNavigationBarHidden = YES;
    /// 隐藏导航栏的细线
    self.prefersNavigationBarBottomLineHidden = YES;
    //设置tableView 的样式
    self.style = UITableViewStyleGrouped;
    //允许上拉刷新 下拉加载
    self.shouldPullDownToRefresh = YES;
    self.shouldPullUpToLoadMore = YES;
    //每页显示的数据条数
    self.perPage = 5;
    //允许多段显示
    self.shouldMultiSections = YES;
    self.shouldEndRefreshingWithNoMoreData = YES;
    self.reloadSectionSubject = [RACSubject subject];

    ///正文点击响应
    self.attributedTapCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(NSDictionary *info) {
        @strongify(self);
        ///链接点击
        if (info[OBMomentLinkUrlKey]) {
            NSLog(@"-----------------链接点击-----------");
        }
        return [RACSignal empty];
    }];
    ///用户个人信息请求
    self.userProfileCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [self requestUserProfileData];
    }];
    
}
//请求指定页面的网络数据
- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self);
        if (page == 1) {
            //第一次就将所有的数据加载出来
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [[OBDataRequest request]requestWithURL:@"http://thoughtworks-ios.herokuapp.com/user/jsmith/tweets?page=5" params:nil httpMethod:@"GET" completionblock:^(id  _Nonnull result) {
                NSArray *models = [OBMomentModel mj_objectArrayWithKeyValuesArray:result];
                NSLog(@"----已经加载第%zd页的数据----",self.page);
                ///转化数据
                NSArray *viewModels = @[];
                if (models.count > 0) {
                    viewModels = [[models.rac_sequence filter:^BOOL(OBMomentModel *momentModel) {
                        return (momentModel.error.length == 0 && momentModel.unknownError.length == 0);
                    }]map:^OBMomentItemViewModel *(OBMomentModel *momentModel) {
                        @strongify(self);
                        OBMomentItemViewModel *itemViewModel = [[OBMomentItemViewModel alloc]initWithMoment:momentModel];
                        itemViewModel.reloadSectionSubject = self.reloadSectionSubject;
                        itemViewModel.attributedTapCommand = self.attributedTapCommand;
                        return itemViewModel;
                    }].array;
                }
//                if (page==1) {
//                    self.dataSource = viewModels ?:@[];
//                }else{
//                    //// 类似于拼接
//                    self.dataSource = @[ (self.dataSource ?:@[]).rac_sequence , viewModels.rac_sequence].rac_sequence.flatten.array;
//                }
                ///数据重组
                [self array2dWithArray:viewModels];
                ///设置数据源
                [self setCurrentDataWithPage:page];
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
            } failedBlock:^(id  _Nonnull error) {
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
            }];
        } else {
            [self setCurrentDataWithPage:page];
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        }
        return nil;
    }];
    
}
//请求用户信息
- (RACSignal *)requestUserProfileData
{
    @weakify(self);
    return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self);
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [[OBDataRequest request]requestWithURL:@"http://thoughtworks-ios.herokuapp.com/user/jsmith" params:nil httpMethod:@"GET" completionblock:^(id  _Nonnull result) {
            OBUserModel *userModel = [OBUserModel mj_objectWithKeyValues:result];
            OBMomentProfileViewModel *viewModel = [[OBMomentProfileViewModel alloc]initWithUser:userModel];
            self.profileViewModel = viewModel;
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        } failedBlock:^(id  _Nonnull error) {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        }];
        return nil;
    }]deliverOnMainThread];
}
 ///将数组转化为二维数组 方便后面取值
- (void)array2dWithArray:(NSArray *)viewModels
{
    NSMutableArray *array2d = [NSMutableArray array];
    NSMutableArray *array = nil;
    for (int i = 0; i <viewModels.count; i++) {
        if (i % self.perPage == 0) {
            array = [NSMutableArray array];
            [array2d addObject:array];
        }
        [array addObject:viewModels[i]];
    }
    self.allItemViewModels = array2d;
}
///设置数据源
- (void)setCurrentDataWithPage:(NSUInteger)page
{
    if (self.allItemViewModels.count >= page) {
        if (page == 1) {
            //第一条
            //取第一个
            self.dataSource = self.allItemViewModels[page - 1];
        } else {
            //第几页就拼接第几页
            NSMutableArray *array = self.allItemViewModels[page-1];
            self.dataSource = @[ (self.dataSource ?:@[]).rac_sequence , array.rac_sequence].rac_sequence.flatten.array;
        }
    }
    
}
@end

